[英]C++ Class with 2 template arguments, function with 1 argument
Is there any way to call a class member function that takes only 1 template argument instead of 2?有什么方法可以调用 class 成员 function,它只需要 1 个模板参数而不是 2 个?
I would like to write some code like this:我想写一些这样的代码:
template<typename T, size_t N>
void Container<int, N>::quick_sort() {
}
You cannot partial specialize a method, you could partial specialize the whole class, but require some duplication.您不能部分特化一个方法,您可以部分特化整个 class,但需要一些重复。
template<typename T, size_t N>
class Container
{
// Some code ...
void quick_sort();
};
template <typename T,size_t N>
void Container<T, N>::quick_sort()
{
// ...
}
// Class specialization
template <size_t N>
class Container<int, N>
{
// Some similar/same code...
void quick_sort();
};
template <size_t N>
void Container<int, N>::quick_sort()
{
// ...
}
As alternative, C++17 allows作为替代方案,C++17 允许
template<typename T, size_t N>
class Container
{
// Some code ...
void quick_sort()
{
if constexpr (std::is_same_v<int, T>) {
// ...
} else {
// ...
}
}
};
For prior versions, regular if
would probably produces error (both branches should be valid, even if not taken).对于以前的版本,常规
if
可能会产生错误(两个分支都应该有效,即使没有被采用)。
So tag dispatching is an easy approach (SFINAE is another one):所以标签调度是一种简单的方法(SFINAE 是另一种方法):
template <typename> struct Tag{};
template<typename T, size_t N>
class Container
{
private:
void quick_sort(tag<int>)
{
// ...
}
template <typename U>
void quick_sort(tag<U>)
{
// ...
}
public:
void quick_sort()
{
quick_sort(Tag<T>());
}
// Some code ...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.