我可以运行此代码,但是当我启用3个已注释的行时,它不再编译并出现以下错误:
1>d:\git\testprojekt\testprojekt\testprojekt.cpp(41): warning C4346: 'first_argument<F>::type': dependent name is not a type
1> d:\git\testprojekt\testprojekt\testprojekt.cpp(41): note: prefix with 'typename' to indicate a type
1> d:\git\testprojekt\testprojekt\testprojekt.cpp(43): note: see reference to class template instantiation 'Bla<Type>' being compiled
1>d:\git\testprojekt\testprojekt\testprojekt.cpp(41): error C2923: 'DoStuff': 'first_argument<F>::type' is not a valid template type argument for parameter 'Arg'
1> d:\git\testprojekt\testprojekt\testprojekt.cpp(22): note: see declaration of 'first_argument<F>::type'
我的想法为什么它不起作用是编译器想要确保Bla编译各种模板参数,但first_argument只能处理具有operator()定义的模板参数。 有谁知道如何让这个例子有效? 我需要它来选择一个类,这里是doStuff,基于模板参数operator()是否接受一个参数,在另一个模板化的类中,这里是Bla。
#include <iostream>
template<typename F, typename Ret>
void helper(Ret(F::*)());
template<typename F, typename Ret>
void helper(Ret(F::*)() const);
template<typename F, typename Ret, typename A, typename... Rest>
char helper(Ret(F::*)(A, Rest...));
template<typename F, typename Ret, typename A, typename... Rest>
char helper(Ret(F::*)(A, Rest...) const);
template<typename F>
struct first_argument {
typedef decltype(helper(&F::operator())) type;
};
template <typename Functor, typename Arg = first_argument<Functor>::type>
struct DoStuff;
template <typename Functor>
struct DoStuff<Functor, char>
{
void print() { std::cout << "has arg" << std::endl; };
};
template <typename Functor>
struct DoStuff<Functor, void>
{
void print() { std::cout << "does not have arg" << std::endl; };
};
template <typename Type>
struct Bla
{
//DoStuff<typename Type> doStuff;
//void print() { doStuff.print(); };
};
int main()
{
struct functorNoArg {
void operator() () {};
};
struct functorArg {
void operator()(int a) { std::cout << a; };
};
auto lambdaNoArg = []() {};
auto lambdaArg = [](int a) {};
std::cout << std::is_same<first_argument<functorArg>::type,int>::value <<std::endl; // this works
DoStuff<functorArg> doStuff;
doStuff.print();
DoStuff<functorNoArg> doStuff2;
doStuff2.print();
DoStuff<decltype(lambdaArg)> doStuff3;
doStuff3.print();
DoStuff<decltype(lambdaNoArg)> doStuff4;
doStuff4.print();
Bla<functorArg> bla;
//bla.print();
return 0;
}
感谢所有模板书呆子帮助:)
答案 0 :(得分:1)
在struct Bla
中,您应该说DoStuff<Type> doStuff;
(此处不需要或不允许使用typename)。
In(更正版):
template <typename Functor, typename Arg = typename first_argument<Functor>::type>
struct DoStuff;
typename
之前您遗失了first_argument<Functor>::type
。