c++ - 类型和非类型模板特化

标签 c++ metaprogramming template-meta-programming c++17

我想为一个类型和一个函数编写一个 MP 预测器。好像有什么不合法的地方:

#include <iostream>

template <class R>
struct X { 
    static constexpr int value = 0;
};

// Specialization for type
template <>
struct X<int(int)> {
    static constexpr int value = 1;
};

// ERROR: Redefinition with diffrent kind
template <int (*F)(int)>
struct X { 
    static constexpr int value = 2;
};

int fun(int);

int main(int, char* []) 
{
    std::cout << "X<int>: " << X<int>::value << '\n';
    std::cout << "X<int(int)>: " << X<int(int)>::value << '\n';
    std::cout << "X<decltype(fun)>: " << X<decltype(fun)>::value << '\n';
    std::cout << "X<fun>: " << X<fun>::value << '\n';
    return 0;
}

是否有可能实现这样的目标?

更多详情: 有什么用?

  1. 学习元编程
  2. 编写一个通用预测器,它可以判断是否使用给定参数调用函数/对象实例(类似于 C++17 中的 is_callable)

最佳答案

Is it possible to achieve something like that?

您实际上是在询问是否可以重载类模板。你不能。

但是,你当然可以重载函数模板——你可以有一个函数模板,它接受一个非推导模板类型参数,特化它,然后有另一个函数模板接受一个非推导模板非类型参数:

#include <iostream>

template <class R> constexpr int X() { return 0; }    

// specialization for type
template <> constexpr int X<int(int)>() { return 1; }

// Redefinition with different kind
template <int (*F)(int)>
constexpr int X() { return 2; }

int fun(int);

int main(int, char* []) 
{
    std::cout << "X<int>: " << X<int>() << std::endl;
    std::cout << "X<int(int)>: " << X<int(int)>() << std::endl;
    std::cout << "X<decltype(fun)>: " << X<decltype(fun)>() << std::endl;
    std::cout << "X<fun>: " << X<fun>() << std::endl;
    return 0;
}

根据需要打印 0、1、1 和 2。

关于c++ - 类型和非类型模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488319/

相关文章:

c++ - 函数模板重载谜题

c++ - 构造函数引用参数导致段错误

C++ 包含 Guard 奇怪的行为?

prolog - 序言中的深度有限搜索( Vanilla 元解释器)

python - 在使用 `types.new_class` 创建的类上设置模块

c++ - 为什么在分解 std::tuple 时需要 std::integral_constant?

c++ - C++ 是否支持归纳类型定义?

c++ - 在哪里可以找到 GNU stdc++ operator new 的源代码?

c++ - 构建一个 vector 以允许未初始化的存储

c# - 在属性中,如何获取它所附加的方法的名称?