具有非类型模板参数的函数模板中的 static_assert

Tru*_*uLa 1 c++ templates static-assert template-specialization

我有一个带有整数模板参数的函数模板。我想仅提供特定整数的实现。尝试将函数模板与另一个参数一起使用应该会导致编译错误。

static_assert以下面介绍的方式使用。

#include <type_traits>
#include <iostream>

template <typename T>
struct false_type : public std::false_type {};

template <int T>
void function() {
    static_assert(false_type<decltype(T)>::value, "Error");
};

template <>
void function<1>() {
    std::cout << 1 << std::endl;
}

int main() {
    function<1>();
}
Run Code Online (Sandbox Code Playgroud)

该代码运行良好,直到gcc 9.1它给出一个error: static assertion failed.

我想知道是否有一种技术可以实现我的目标并且与 兼容gcc 9.1

asc*_*ler 5

static_assert一个参数是非依赖假常量的 A 总是“格式错误,不需要诊断”,即使在从未实例化的模板中也是如此。(所以 g++ 和 clang++ 在这里都不是“不正确的”。)在你的函数模板中,T是值相关的,但不是类型相关的(它的类型始终是int),所以decltype(T)是 不相关的,并且 也不是false_type<int>::value

你能false_type简单地也接受一个int参数吗?

#include <type_traits>
#include <iostream>

template <int>
struct false_type : public std::false_type {};

template <int T>
void function() {
    static_assert(false_type<T>::value, "Error");
};

template <>
void function<1>() {
    std::cout << 1 << std::endl;
}

int main() {
     function<1>();
}
Run Code Online (Sandbox Code Playgroud)