C++ 为什么可以';是否可以推导嵌套在模板类中的枚举的模板参数?
我有一些常量的名称如下:C++ 为什么可以';是否可以推导嵌套在模板类中的枚举的模板参数?,c++,templates,c++11,C++,Templates,C++11,我有一些常量的名称如下: template<int n> class usart { private: usart(); public: enum class tx {}; enum class rx {}; enum class ck {}; }; template<> class usart<1> { public: enum class tx { A9 = gpio::A9, C4 = gpio::C4 };
template<int n> class usart {
private:
usart();
public:
enum class tx {};
enum class rx {};
enum class ck {};
};
template<> class usart<1> {
public:
enum class tx { A9 = gpio::A9, C4 = gpio::C4 };
enum class rx { A10 = gpio::A10, C5 = gpio::C5 };
enum class ck { A8 = gpio::A8 };
};
// two more of these
但是,当我将此用于
USART us = USART(usart<1>::tx::A9, usart<1>::rx::A10);
为什么这种语法是非法的?
编辑:typename
现在,当我尝试实例化该类时,会出现以下错误:
错误:调用“USART::USART(USART::tx,USART::rx)”时没有匹配的函数
注:模板USART::USART(类型名称USART::tx,类型名称USART::rx)
注意:模板参数扣除/替换失败:
注意:无法推断模板参数“N”
函数参数中使用的模板参数是不可推断的,因为参数是依赖类型 “但那太傻了!”你会说;“很明显,N是1!为什么编译器不能聪明地推断出这一点?” 考虑以下几点:
template<> class usart<4321> {
public:
typedef usart<1>::tx tx;
typedef usart<1>::rx rx;
typedef usart<1>::ck ck;
};
模板类usart{
公众:
typedef usart::tx;
类型定义usart::rx;
typedef usart::ck;
};
N应该是1还是4321?毕竟,usart::tx
和usart::tx
是同一种类型
如果不检查usart的一个实例化是否具有与
tx
成员相同的类型,编译器就无法知道N应该是什么。这要么需要太多的实例化,要么需要太复杂的逻辑来证明在一般情况下没有实例化会导致这种情况。当然,对于这个特定的情况,实现一些东西可能很简单,但对于所有其他情况,这并不是非常有用。C++委员会只是决定不需要编译器编写者。< /P> YEP,添加<代码> TypEnMaE<代码>修复了错误,但是现在我得到了<代码>没有匹配函数来调用“USAT::USAT(UART::TX,USAT::RX)”/Calp>@ SBI:我没有立即看到这与我的问题之间的联系。既然还没有人回答,你为什么不相应地改变你的问题呢?请指明发生错误消息的确切位置。我很抱歉现在投票结果很接近。如果可以的话,我会收回的。这是不可推断的背景。基本上,您不能期望从Foo::Y
@R.MartinhoFernandes中检索X
:也许usart
可以包含一个无友函数,该函数接受usart::tx
并返回类型usart
。然后,如果USART
执行decltype(该函数(pin_tx))
,则它将获得一个可以从中推断出N
的类型。如果有人在你的回答中做了这件事,那么就会推断出1
(如果他们没有定义朋友)或者电话不明确(如果他们这样做了),从而诊断出他们的错误。不过,我不太清楚如何将所有这些放在一起,这可能需要USART进行额外的间接处理。这很有意义。我想我会对usart1::tx
,usart2:tx
等使用重载,因为我并没有从这里的模板参数中获得任何东西。
error: expected ')' before 'pin_tx'
error: no matching function for call to 'USART::USART(usart<1>::tx, usart<1>::rx)'
note: template<int N> USART::USART(typename usart<N>::tx, typename usart<N>::rx)
note: template argument deduction/substitution failed:
note: couldn't deduce template parameter 'N'
template<> class usart<4321> {
public:
typedef usart<1>::tx tx;
typedef usart<1>::rx rx;
typedef usart<1>::ck ck;
};