是否可以将引用类型传递给模板以指定以下非类型模板参数的类型?
Can I pass a reference type to a template to specify following non-type template parameters' types?
考虑一个例子:
#include <type_traits>
template <class T, T>
struct has_duplicates_info { };
template <class T, T...>
struct has_duplicates;
template <class T, T First, T... Others>
struct has_duplicates<T, First, Others...>:
has_duplicates<T, Others...>,
has_duplicates_info<T, First> {
static constexpr bool value =
std::is_base_of<has_duplicates_info<T, First>, has_duplicates<T, Others...>>::value
|| has_duplicates<T, Others...>::value;
};
template <class T, T Last>
struct has_duplicates<T, Last>: has_duplicates_info<T, Last>, std::false_type { };
int a, b;
int main() {
static_assert(!has_duplicates<int, 0, 1, 2>::value, "has_duplicates<int, 0, 1, 2>::value");
static_assert(has_duplicates<int, 1, 2, 2, 3>::value, "!has_duplicates<int, 1, 2, 2, 3>::value");
static_assert(has_duplicates<int&, a, a, b>::value, "!has_duplicates<int&, a, a, b>::value");
}
在clang中可以很好地编译,但在gcc中不行。问题在一行:
static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value");
编译器提示has_duplicates<int&, a, a, b>
是不完全类型:
has_duplicates.cc:26:18: error: incomplete type ‘has_duplicates<int&, a, a, b>’ used in nested name specifier static_assert(has_duplicates<int&, a, a, b>::value, "has_duplicates<int&, a, a, b>::value"); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
所以…哪个编译器是正确的?
编辑:澄清一下,我是不是试图检查传递给has_duplicates
的变量背后的运行时值是否包含重复,只有当有重复的引用传递给这个trait时…例如,下面的代码可以在gcc和clang中成功编译:
template <int &X>
struct a { };
int b;
int main() {
a<b> c;
}
首先,这肯定是gcc中的一个bug。您对错误本质的诊断几乎是正确的,但并不是gcc不接受引用类型的非类型模板参数,而是gcc无法识别引用类型的非类型模板参数作为类模板的部分专门化,其中引用类型是上一个模板参数:
template<int, class T, T> struct S; // #1
template<class T, T A> struct S<0, T, A> {}; // #2
int i;
S<0, int&, i> s; // #3 error: aggregate 'S<0, int&, i> s' has incomplete type
#2
是#1
的完全合法的部分专门化,应该由实例化#3
匹配,per [temp.class.spec]。匹配]和[temp.扣除].
幸运的是,有一个简单的解决方法,那就是为引用类型提供进一步的部分专门化:
template<class R, R& A> struct S<0, R&, A> {};
像clang这样的正确的编译器也会很好。
在您的情况下,进一步的部分专门化将是:
template <class R, R& First, R&... Others>
struct has_duplicates<R&, First, Others...> // ...
template <class R, R& Last>
struct has_duplicates<R&, Last> // ...
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法