【问题标题】:Understanding a "template argument is invalid" error message了解“模板参数无效”错误消息
【发布时间】:2012-11-12 13:48:46
【问题描述】:

考虑代码:

#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;

}

我要做的是创建一个元函数来测试“可调用性”的特定定义。现在我被困在 GCC 4.5.3 上的 compilation error 上:

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

这是什么意思?为什么我可以专攻decltype(Functor().Invoke()),却不能专攻decltype(Functor().Invoke&lt;void&gt;())

【问题讨论】:

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


    【解决方案1】:

    由于解析不明确,您需要使用template 对其进行限定:

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

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

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

    【讨论】:

    • 非常感谢!这有帮助。
    猜你喜欢
    • 2010-09-08
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    相关资源
    最近更新 更多