模板需要子句失败
我有一组大致定义如下的类:
template <typename U>
class Iterable {
// More code
};
class Container : public Iterable<Element> {
// More code
};
class Tuple : public Container {
// More code
};
class List {
public:
template <typename I, typename T>
requires std::is_base_of_v<Iterable<T>,I>
explicit List(const I& i) {
for (const T& e : i) elems_.emplace_back(e,true);
}
// More code
};
尝试从tuple
创建list
,因为
Tuple t1(1,2,3);
List l1(t1);
给出以下填充消息,
/home/felix/git/libraries/cpp_script/tests/test_list.cpp:96:15: error: no matching function for call to ‘cs::List::List(cs::Tuple&)’
96 | List l1(t1);
| ^
In file included from /home/felix/git/libraries/cpp_script/tests/test_list.cpp:3:
/home/felix/git/libraries/cpp_script/include/list.hpp:72:10: note: candidate: ‘template<class I, class T> requires is_base_of_v<cs::Iterable<T>, I> cs::List::List(const I&)’
72 | explicit List(const I& i) {
| ^~~~
/home/felix/git/libraries/cpp_script/include/list.hpp:72:10: note: template argument deduction/substitution failed:
/home/felix/git/libraries/cpp_script/tests/test_list.cpp:96:15: note: couldn’t deduce template parameter ‘T’
96 | List l1(t1);
| ^
我不明白为什么替换失败了。 i ==元组
和t ==元素
应满足requie
条款,就可以了。
I have a set of classes roughly defined as follows:
template <typename U>
class Iterable {
// More code
};
class Container : public Iterable<Element> {
// More code
};
class Tuple : public Container {
// More code
};
class List {
public:
template <typename I, typename T>
requires std::is_base_of_v<Iterable<T>,I>
explicit List(const I& i) {
for (const T& e : i) elems_.emplace_back(e,true);
}
// More code
};
Trying to create a List
from Tuple
as
Tuple t1(1,2,3);
List l1(t1);
gives the following complilation message
/home/felix/git/libraries/cpp_script/tests/test_list.cpp:96:15: error: no matching function for call to ‘cs::List::List(cs::Tuple&)’
96 | List l1(t1);
| ^
In file included from /home/felix/git/libraries/cpp_script/tests/test_list.cpp:3:
/home/felix/git/libraries/cpp_script/include/list.hpp:72:10: note: candidate: ‘template<class I, class T> requires is_base_of_v<cs::Iterable<T>, I> cs::List::List(const I&)’
72 | explicit List(const I& i) {
| ^~~~
/home/felix/git/libraries/cpp_script/include/list.hpp:72:10: note: template argument deduction/substitution failed:
/home/felix/git/libraries/cpp_script/tests/test_list.cpp:96:15: note: couldn’t deduce template parameter ‘T’
96 | List l1(t1);
| ^
I don't understand why the substitution fails. I==Tuple
and T==Element
should satisfy the require
clause just fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的示例不起作用,因为没有办法推断出
t
的类型。如果要限制
i
从base类继承iToble&lt; u&gt;
对于某些类型u
,您可能需要做demo
Your example won't work because there is no way to deduce the type of
T
.If you want to constrain
I
to inherit from base classIterable<U>
for some typeU
, you might want to doDemo