【发布时间】:2013-01-28 09:50:28
【问题描述】:
我有一些这样命名的常量:
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
其中gpio 只是一个简单的整数枚举。
我想在另一个文件中对我的类强制执行一些类型安全:
class USART {
public:
template<int N>
USART(typename usart<N>::tx pin_tx, typename usart<N>::rx pin_rx) {
//This signature enforces correct pins with types, doesn't it?
}
};
但是,当我使用它时
USART us = USART(usart<1>::tx::A9, usart<1>::rx::A10);
我收到错误
error: expected ')' before 'pin_tx'
为什么这个语法是非法的?
编辑:typename
当我尝试实例化该类时,这会给我这个错误:
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'
【问题讨论】:
-
是的,添加
typenmae修复了该错误,但现在我得到no matching function for call to 'USART::USART(usart<1>::tx, usart<1>::rx)' -
@sbi:我没有立即看到这与我的问题之间的联系
-
嗯。既然还没有人回答,你为什么不相应地改变你的问题呢?请指出确切的错误消息发生在哪里。我很抱歉现在投票接近。如果可以的话,我会收回它。
-
这是非推断上下文。基本上,您不能指望从
Foo<X>::Y检索X。 -
@R.MartinhoFernandes: 也许
usart<N>可以包含一个接受usart<N>::tx并返回类型usart<N>的免费朋友函数。然后如果USART执行decltype(that_function(pin_tx)),它会得到一个类型,可以从中推导出N。如果有人在你的回答中做了这件事,那么推论出1(如果他们也没有定义朋友)或者调用是模棱两可的(如果他们这样做了),这会诊断出他们的错误。不过,我不太确定如何将所有这些放在一起,但它可能需要额外的 USART 间接级别。