了解“模板参数无效”错误消息

时间:2012-11-12 13:48:47

标签: c++ gcc c++11 template-meta-programming sfinae

考虑代码:

#include <type_traits>
#include <iostream>

struct test1 {
    void Invoke() {};
};

struct test2 {
    template<typename> void Invoke() {};
};


enum class InvokableKind {
    NOT_INVOKABLE,
    INVOKABLE_FUNCTION,
    INVOKABLE_FUNCTION_TEMPLATE
};

template<typename Functor, class Enable = void>
struct get_invokable_kind {
    const static InvokableKind value = InvokableKind::NOT_INVOKABLE;
};

template<typename Functor>
struct get_invokable_kind<
  Functor,
  decltype(Functor().Invoke())
  >
{
    const static InvokableKind value = InvokableKind::INVOKABLE_FUNCTION;
};

template<typename Functor>
struct get_invokable_kind<
  Functor,
  decltype(Functor().Invoke<void>())
  >
{
    const static InvokableKind value = InvokableKind::INVOKABLE_FUNCTION_TEMPLATE;
};


int main() {
    using namespace std;

    cout << (get_invokable_kind<test1>::value == InvokableKind::INVOKABLE_FUNCTION) << endl;
    cout << (get_invokable_kind<test2>::value == InvokableKind::INVOKABLE_FUNCTION_TEMPLATE) << endl;

}

我要做的是创建一个元函数来测试“invokability”的特定定义。现在我在GCC 4.5.3上坚持compilation error

  

prog.cpp:37:3:错误:模板参数2无效

这是什么意思?为什么我可以专注于decltype(Functor().Invoke()),但不能专注于decltype(Functor().Invoke<void>())

1 个答案:

答案 0 :(得分:6)

由于解析歧义,您需要使用template对其进行限定:

 decltype(Functor().template Invoke<void>())
                    ^^^^^^^^

相关:Where and why do I have to put the "template" and "typename" keywords?

另外,请考虑使用std::declval而不是Functor()构造函数。

相关问题