设想两个类,StaticFoo和NonStaticFoo,它们是相同的,只是类成员在StaticFoo中是静态的,而在NonStaticFoo中不是静态的。
简单的例子:
class StaticFoo {
static void bar();
static int v;
};
class NonStaticFoo {
void bar();
int v;
};
是否可以筛选出模板类Foo以避免代码重复?
这样我们就可以像
using StaticFoo = Foo<true>;
using NonStaticFoo = Foo<false>;
我四处寻找一个很好的解决方案,以避免模板类每次规格化时的代码重复。
下面是一个示例代码:
template<class T>
class C
{
int foo();
}
现在是默认值的定义:
template<class T>
C<T>::foo() { return 0; }
现在,特殊模板的规格化
template<> C<int>::foo() { ... do a lot of stuff and return n .... }
template<> C<double>::foo() {
我有这样的代码(“宇宙飞船”-like操作符)。
template <class T>
int comparator(const T &a, const T &b){
if (a < b){
return -1;
}else if (a > b){
return +1;
}
return 0;
}
inline int comparator(const char *a, const char *b){
return strcmp(a, b); // I never tried t
以下代码编译良好,但会产生链接器错误:
class Base {};
class Derived : public Base {};
template <typename T>
void f(const T& value);
template <>
void f(const Base& value) {
// ...
}
int main() {
Base b;
f(b);
Derived d;
f(d); // This line causes linker error.
return 0;
我有一个包含另一个类模板的类模板,并且内部模板具有显式的专门化:
template <typename Outer>
struct ContainingClass {
template <typename T>
struct Rule {
Rule(T value);
// ... other members ...
};
template <>
struct Rule<void> {
Rule();
// ... different members than the non-void R
我想写5个不同的类,每个类都有许多完全相同的成员函数,除了一个,每个类都是特殊的。我能写这个避免代码重复吗?
你好,阿列克谢
下面是我的代码的一个非常短的版本,它抛出了错误:
template_test.cpp:15:35: error: invalid use of incomplete type ‘class impl_prototype<cl, 1>
#include <iostream>
using namespace std;
template <int cl, int dim>
class impl_prototype {
public:
我有一个使用模板的多文件项目。
// Foo.h
template <class T>
class Foo
{
T bar;
};
我有一个类(例如Cup)和一组该类的子类。
// Cup.h
class Cup
{
};
class Chalice : public Cup
{
};
class SippyCup : public Cup
{
};
// ...etc.
在模板的.cpp文件中,我需要列出所有可能的模板实现,以避免链接器错误。这是我从那里学到的。
//Foo.cpp
template class Foo<Cup>;
template cl
我们正在使用一个内部库,其中包含一个用于将VariableValue对象列表转换为字符串的StringBuilder类。可以从任意类型(通过专门化convertVariable模板函数)构造VariableValue对象。下面是描述场景的代码:
struct VariableValue {
// Construct a 'VariableValue' object, a variant type which can represent values of
// one of four types: string, number (integer), boolean an
我正在构建一个使用表达式模板的库,在其中我大量使用类中的模板函数。我所有的代码都在运行,最近我决定让主类模板化,以便能够在不同类型的数据上使用它。然而,我不能再专攻我的职能了。我该怎么解决这个问题?我附上了一个显示问题的小测试程序。
我以前的Animal类没有模板化,然后这段代码可以正常工作。
#include<iostream>
#include<vector>
// Example templated class with templated function
template<class T>
class Animals
{
public:
我尝试实现一个模板类,并希望将其限制为特定于某个给定的模板类。例如,在下面的代码中,我希望定义模板类CTest,该模板类只能专用于某些模板参数T的std::vector<T>。对于其他模板参数,类应该是未定义的。如何实现模板类?
// the interface should be something like following
//template <typename std::vector<T> >
//class CTest<std::vector<T> >;
int main(int argc, char* argv[
已经有一些类似的问题已经在堆栈溢出上,但似乎没有直接回答我的问题。如果我转帖了,我真的很抱歉。
我想用这些方法的部分模板专门化来重载模板化类的一些方法(带有两个模板参数)。我还没能弄清楚正确的语法,我开始认为这是不可能的。我想我应该在这里发帖,看看能不能得到确认。
示例代码如下:
template <typename T, typename U>
class Test
{
public:
void Set( T t, U u );
T m_T;
U m_U;
};
// Fully templated method that should be use