Extract class from static and templated member functions - c++

Consider the following code:
#include <iostream>
#include <type_traits>
#include <typeinfo>
struct object
{
void f0(int i) {std::cout<<i<<std::endl;}
void f1(int i) const {std::cout<<i<<std::endl;}
void f2(int i) volatile {std::cout<<i<<std::endl;}
void f3(int i) const volatile {std::cout<<i<<std::endl;}
constexpr int f4(int i) const noexcept {return i;}
static void f5(int i) {std::cout<<i<<std::endl;}
template <class T> void f(T i) {std::cout<<i<<std::endl;}
};
template <class T, class C>
void print_class_containing(T C::* ptr)
{
std::cout<<"typeid(C).name() = "<<typeid(C).name()<<std::endl;
}
int main(int argc, char* argv[])
{
std::cout<<"typeid(object).name() = "<<typeid(object).name()<<std::endl;
print_class_containing(&object::f0);
print_class_containing(&object::f1);
print_class_containing(&object::f2);
print_class_containing(&object::f3);
print_class_containing(&object::f4);
//print_class_containing(&object::f5); -> Not compiling
//print_class_containing(&object::f); -> Not compiling
return 0;
}
How to write a function, and how to call it, to print the class that is "containing" a pointer to static member function (f5), and pointer to templated member function (f)?
Currently, the compiler returns:
static_member.cpp:30:5: error: no matching function for call to 'print_class_containing'
print_class_containing(&object::f5); // -> Not compiling
^~~~~~~~~~~~~~~~~~~~~~
static_member.cpp:17:6: note: candidate template ignored: could not match 'T C::*' against 'void (*)(int)'
void print_class_containing(T C::* ptr)
^
static_member.cpp:31:5: error: no matching function for call to 'print_class_containing'
print_class_containing(&object::f); // -> Not compiling
^~~~~~~~~~~~~~~~~~~~~~
static_member.cpp:17:6: note: candidate template ignored: couldn't infer template argument 'T'
void print_class_containing(T C::* ptr)
^
2 errors generated.

Related

explicit template specialization from function template not working

I am trying to do explicit specialization for a template function called from another template function. Following is a minimum non-working example and I am trying to implement the following idea:
CInt, CDouble and CStr are equivalent of operations that I need to perform. But, CStr constructor expects a little different format.
MyClass is equivalent of a factory, which when requested will return one of the instances of CInt, CDouble or CStr.
The motivation for this structure: Assume that GetCClass function is called from a function with ~100 lines and only one difference: the type of class. The values returned from GetCClass have same APIs.
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class CStrArg {
public:
const char* a;
int size;
};
class MyClass {
public:
class CStr;
class CInt;
class CDouble;
template <typename T>
typename T::Ptr GetCClass(typename T::ArgType arg);
template <typename T>
typename T::Ptr GetCClassInternal(typename T::ArgType arg);
};
class MyClass::CInt {
public:
typedef int ArgType;
typedef shared_ptr<CInt> Ptr;
static Ptr CreatePtr(ArgType i) { return Ptr(new CInt(i)); }
private:
CInt(ArgType i) : i_(i) {}
ArgType i_;
};
class MyClass::CDouble {
public:
typedef double ArgType;
typedef shared_ptr<CDouble> Ptr;
static Ptr CreatePtr(ArgType d) { return Ptr(new CDouble(d)); }
private:
CDouble(ArgType i) : i_(i) {}
ArgType i_;
};
class MyClass::CStr {
public:
typedef CStrArg ArgType;
typedef shared_ptr<CStr> Ptr;
static Ptr CreatePtr(string s) { return Ptr(new CStr(s)); }
private:
CStr(string i) : i_(i) {}
string i_;
};
//template definition
template <typename T>
typename T::Ptr MyClass::GetCClass(typename T::ArgType arg) {
return GetCClassInternal(arg);
}
template <typename T>
typename T::Ptr MyClass::GetCClassInternal(typename T::ArgType arg) {
cout << "GetCClass for all types but one" << endl;
return T::CreatePtr(arg);
}
template <>
MyClass::CStr::Ptr MyClass::GetCClassInternal<MyClass::CStr>(CStrArg arg) {
return CStr::CreatePtr(arg.a);
}
int main() {
MyClass test;
int i = 5;
double d = 1.2;
CStrArg s;
s.a = "why me";
s.size = 6;
auto iptr = test.GetCClass(i);
auto dptr = test.GetCClass(d);
auto sptr = test.GetCClass(s);
return 0;
}
I get the following error:
experimental/amandeep/proto_test/fn_template_sp.cc:88:31: note: candidate is:
experimental/amandeep/proto_test/fn_template_sp.cc:20:19: note: template<class T> typename T::Ptr MyClass::GetCClass(typename T::ArgType)
typename T::Ptr GetCClass(typename T::ArgType arg);
^
experimental/amandeep/proto_test/fn_template_sp.cc:20:19: note: template argument deduction/substitution failed:
experimental/amandeep/proto_test/fn_template_sp.cc:88:31: note: couldn't deduce template parameter ‘T’
auto iptr = test.GetCClass(i);
^
experimental/amandeep/proto_test/fn_template_sp.cc:89:31: error: no matching function for call to ‘MyClass::GetCClass(double&)’
auto dptr = test.GetCClass(d);
^
experimental/amandeep/proto_test/fn_template_sp.cc:89:31: note: candidate is:
experimental/amandeep/proto_test/fn_template_sp.cc:20:19: note: template<class T> typename T::Ptr MyClass::GetCClass(typename T::ArgType)
typename T::Ptr GetCClass(typename T::ArgType arg);
^
experimental/amandeep/proto_test/fn_template_sp.cc:20:19: note: template argument deduction/substitution failed:
experimental/amandeep/proto_test/fn_template_sp.cc:89:31: note: couldn't deduce template parameter ‘T’
auto dptr = test.GetCClass(d);
^
experimental/amandeep/proto_test/fn_template_sp.cc:90:31: error: no matching function for call to ‘MyClass::GetCClass(CStrArg&)’
auto sptr = test.GetCClass(s);
^
experimental/amandeep/proto_test/fn_template_sp.cc:90:31: note: candidate is:
experimental/amandeep/proto_test/fn_template_sp.cc:20:19: note: template<class T> typename T::Ptr MyClass::GetCClass(typename T::ArgType)
typename T::Ptr GetCClass(typename T::ArgType arg);
^
experimental/amandeep/proto_test/fn_template_sp.cc:20:19: note: template argument deduction/substitution failed:
experimental/amandeep/proto_test/fn_template_sp.cc:90:31: note: couldn't deduce template parameter ‘T’
auto sptr = test.GetCClass(s);
I have read multiple answers, but I cannot understand why this is not working. Any help is appreciated.
EDIT:
I cannot understand, but locally in my actual code I get the following:
/home/workspace/main/util/storage/smb2_proxy/smb2_proxy.cc:239:29: error: template-id ‘CreateOp<storage::smb2_proxy::Smb2Proxy::PurgeTaskOp>’ for ‘storage::smb2_proxy::Smb2Proxy::PurgeTaskOp::Ptr storage::smb2_proxy::Smb2Proxy::CreateOp(std::shared_ptr<storage::smb2_proxy::Smb2Proxy::TaskState>,storage::smb2_proxy::Smb2Proxy::PurgeTaskOp::ArgType&,storage::smb2_proxy::Smb2Proxy::PurgeTaskOp::ResultType*,storage::smb2_proxy::Smb2Proxy::DoneCb)’ does not match any template declaration
Smb2Proxy::PurgeTaskOp::Ptr Smb2Proxy::CreateOp<Smb2Proxy::PurgeTaskOp>(
^~~~~~~~~
In file included from /home/workspace/main/util/storage/smb2_proxy/smb2_proxy.cc:5:0:
/home/workspace/main/util/storage/smb2_proxy/smb2_proxy.h:160:20: note: candidate is: template<class Op> typename Op::Ptr storage::smb2_proxy::Smb2Proxy::CreateOp(std::shared_ptr<storage::smb2_proxy::Smb2Proxy::TaskState>, const typename Op::ArgType&, typename Op::ResultType*,storage::smb2_proxy::Smb2Proxy::DoneCb)
typename Op::Ptr CreateOp(std::shared_ptr<TaskState> task_state,
CreateOp -> GetCClassInternal (both are equivalent)
The compiler is not able to take specialization of CreateOp and complains that it does not match any declaration.
PS: I had another question in which I had made a mistake while posting the code. I have deleted the question and am reposting it.
The problem is that the template parameter T of GetCClass (and GetCClassInternal) is used in non-deduced contexts, it can't be deduced.
If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.
1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id:
You can specify the template argument explicitly. e.g.
auto iptr = test.GetCClass<MyClass::CInt>(i);
auto dptr = test.GetCClass<MyClass::CDouble>(d);
auto sptr = test.GetCClass<MyClass::CStr>(s);
LIVE

Explicit instantiation for concept checking

We have:
template<typename T>
struct A {
void foo(int a) {
T::foo(a);
}
};
template<typename T>
struct B {
template struct A<T>; // concept check
};
So, I define a concept checker A that checks T by forwarding foo to T::foo.
Now, I want to check whether the argument passed to B satisfies the concept A by explicit instantiation, but the compiler complains that it's the wrong namespace. How can I fix that?
Something like this perhaps:
template<typename T, void(T::*)(int)>
struct A {};
template<typename T>
struct B {
using Check = A<T, &T::foo>;
};
Demo
Or this:
template<typename T>
struct B {
static_assert(
std::is_same<decltype(&T::foo), void(T::*)(int)>::value,
"No T::foo(int) member");
};
So, I found a working example:
#include <tuple>
template<typename A>
struct IA : A {
void foo(int a) {
A::foo(a);
}
void bar(double a) {
A::bar(a);
}
static constexpr auto $ = std::make_tuple(&IA::foo, &IA::bar);
};
template<typename T>
struct B {
// trigger concept/interface check of T "implements" IA
static constexpr auto $ = IA<T>::$;
};
struct Test {
void foo(int a) {}
void bar(int a, int b) {}
};
int main() {
B<Test> b;
b = b;
}
The generation of $ in the structs triggers the compilation. The compiler in the example above correctly complains with:
In instantiation of 'void IA<A>::bar(double) [with A = Test]':
13:57: required from 'constexpr const std::tuple<void (IA<Test>::*)(int), void (IA<Test>::*)(double)> IA<Test>::$'
18:27: recursively required from 'constexpr const std::tuple<void (IA<Test>::*)(int), void (IA<Test>::*)(double)> B<Test>::$'
18:27: required from 'struct B<Test>'
28:13: required from here
10:17: error: no matching function for call to 'IA<Test>::bar(double&)'
10:17: note: candidate is:
24:10: note: void Test::bar(int, int)
24:10: note: candidate expects 2 arguments, 1 provided

GCC failed with variadic template and pointer to member function

#include <memory>
#include <iostream>
class Manager
{
public:
Manager() {}
virtual ~Manager() {}
int funcA(std::shared_ptr<int> a, float b) { return *a + b; }
int funcA(std::shared_ptr<double> a) { return *a; }
};
template <typename T, typename... Args>
auto resolver(int (Manager::*func)(std::shared_ptr<T>, Args...)) -> decltype(func) {
return func;
}
int main(int, char **)
{
Manager m;
Manager *ptr = &m;
auto var = std::make_shared<int>(1);
int result = (ptr->*resolver<int>(&Manager::funcA))(var, 2.0);
std::cout << result << std::endl;
return 0;
}
This code fail to compile with gcc but is fine with clang.
(gcc 5.3.1 and 6.0.0 20151220).
Do you know if there is any solution to make it compile with gcc ? I tried with template specialization and explicit instantiation.
EDIT: gcc gives the following error:
test > g++ -std=c++11 test.cpp
test.cpp: In function 'int main(int, char**)':
test.cpp:29:52: error: no matching function for call to 'resolver(<unresolved overloaded function type>)'
int result = (ptr->*resolver<int>(&Manager::funcA))(var, 2.0);
^
test.cpp:15:6: note: candidate: template<class T, class ... Args> decltype (func) resolver(int (Manager::*)(std::shared_ptr<_Tp1>, Args ...))
auto resolver(int (Manager::*func)(std::shared_ptr<T>, Args...)) -> decltype(func) {
^
test.cpp:15:6: note: template argument deduction/substitution failed:
test.cpp:29:52: note: mismatched types 'std::shared_ptr<int>' and 'std::shared_ptr<double>'
int result = (ptr->*resolver<int>(&Manager::funcA))(var, 2.0);
^
test.cpp:29:52: note: could not resolve address from overloaded function '& Manager::funcA'
test >
As a workaround, you may use
template <typename T>
struct resolver
{
template <typename... Args>
auto operator ()(int (Manager::*func)(std::shared_ptr<T>, Args...)) -> decltype(func) {
return func;
}
};
With call like
(ptr->*resolver<int>{}(&Manager::funcA))(var, 2.0);
Note the extra {} to call constructor.

Variadic templates and C arrays

I'm trying to compile the following piece of code:
template <typename T, int N> void foo( const T (&array)[N]) {}
template <typename T> static int args_fwd_(T const &t) { foo(t); return 0; }
template<class ...Us> void mycall(Us... args) {
int xs[] = { args_fwd_(args)... };
}
int main(void) {
int b[4];
mycall(b);
}
The mycall function uses variadic templates and then forwards to the args_fwd_ function to call the function foo on each argument.
This works fine for most argument types (assuming I have appropriately defined foo functions). But when I try to pass a C-style array (int b[4]) it gets turned into a pointer and then it can't find the templated foo function that requires an array (not pointer). The error from gcc 4.9.3 is as follows:
error: no matching function for call to ‘foo(int* const&)’
note: candidate is:
note: template<class T, int N> void foo(const T (&)[N])
template <typename T, int N> void foo( const T (&array)[N]) {}
note: template argument deduction/substitution failed:
note: mismatched types ‘const T [N]’ and ‘int* const’
Note the part about looking for a pointer. This is the same in clang as well so apparently this is standard compliant. Is there a way to preserve that this is a C array without it getting converted to a pointer?
Yes. Use perfect forwarding:
#include <utility>
template<class ...Us> void mycall(Us&&... args) {
int xs[] = { args_fwd_(std::forward<Us>(args))... };
}

Partial specialization non-top level cv qualifier ignored in function signature

I'm trying to use something like the following test case:
/* Generic implementation */
template <typename T>
struct SpecWrapper {
static void bar(T const* src) {
printf("src[0] = %le\n", src[0]);
}
};
/* Volatile partial-specialization */
template <typename T>
struct SpecWrapper<T volatile> {
static void bar(T const* src) {
printf("src[0] = %le\n", src[0]);
}
};
/* Instantiate */
void foo(double volatile const* src) {
SpecWrapper<double volatile>::bar(src);
}
However this generates the following error with g++
test.cxx: In function ‘void foo(const volatile double*)’:
test.cxx:18:38: error: invalid conversion from ‘const volatile double*’ to ‘const double*’ [-fpermissive]
LowLevel<double volatile>::bar(src);
^
test.cxx:12:16: error: initializing argument 1 of ‘static void LowLevel<volatile T>::bar(const T*) [with T = double]’ [-fpermissive]
static void bar(T const* src) {
^
Can someone explain why this problem is arising? There are a few workarounds that spring to mind, but I would like to understand why it's a problem in the first place.
Should be
/* Volatile partial-specialization */
template <typename T>
struct SpecWrapper<T volatile> {
static void bar(T volatile const* src) {
printf("src[0] = %le\n", src[0]);
}
};
since T is just double.