2016-05-23 163 views
0

当我使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; 
} 

感谢所有模板书呆子帮助:)

+1

你不把'typename'放在你想要的地方,而你把'typename'放在你不应该在的地方 –

+1

当编译器说你缺少'typename'时,它并不意味着'DoStuff doStuff ;',这意味着'typename Arg = typename first_argument :: type' –

回答

1

在你struct Bla你应该说(无需或这里不允许类型名称)DoStuff<Type> doStuff;

在(修正版):

template <typename Functor, typename Arg = typename first_argument<Functor>::type> struct DoStuff;

你失踪typenamefirst_argument<Functor>::type之前。

+0

啊谢谢,是的,一个typename只是一些愚蠢的东西,我试图做工后,它最初没有工作:P – bodzcount