小编Flu*_*mur的帖子

使用不同对象时模板特化的多重定义

当我在不同的目标文件中使用专用模板时,链接时出现"多重定义"错误.我找到的唯一解决方案涉及使用"内联"功能,但它似乎只是一些解决方法.如何在不使用"inline"关键字的情况下解决这个问题?如果那不可能,为什么?

这是示例代码:

paulo@aeris:~/teste/cpp/redef$ cat hello.h 
#ifndef TEMPLATE_H
#define TEMPLATE_H

#include <iostream>

template <class T>
class Hello
{
public:
    void print_hello(T var);
};

template <class T>
void Hello<T>::print_hello(T var)
{
    std::cout << "Hello generic function " << var << "\n";
}

template <> //inline
void Hello<int>::print_hello(int var)
{
    std::cout << "Hello specialized function " << var << "\n";
}

#endif
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.h 
#include <iostream>

void other_func();
Run Code Online (Sandbox Code Playgroud)
paulo@aeris:~/teste/cpp/redef$ cat other.c 
#include "other.h"

#include "hello.h"

void other_func()
{
    Hello<char> hc;
    Hello<int> hi; …
Run Code Online (Sandbox Code Playgroud)

c++ templates

80
推荐指数
3
解决办法
4万
查看次数

轻松找到未初始化的成员变量

我正在寻找一种简单的方法来查找未初始化的类成员变量.

运行时编译时查找它们都可以.

目前我在类构造函数中有一个断点,并逐个检查成员变量.

c++ findbugs initialization

46
推荐指数
6
解决办法
4万
查看次数

C++中的变量初始化

我的理解是int变量将0自动初始化; 但事实并非如此.下面的代码打印一个随机值.

int main () 
{   
    int a[10];
    int i;
    cout << i << endl;
    for(int i = 0; i < 10; i++)
        cout << a[i] << " ";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  • 什么规则(如果有的话)适用于初始化?
  • 具体来说,在什么条件下变量自动初始化?

c++ variables initialization

42
推荐指数
3
解决办法
6万
查看次数

c ++ - <未解析的重载函数类型>

在我调用的类中Mat,我希望有一个函数,它将另一个函数作为参数.现在我有以下4个函数,但是在调用print()时遇到错误.第二行给了我一个错误,但我不明白为什么,因为第一行有效.唯一的区别是函数f不是类的成员Mat,而是f2.失败的是:error: no matching function for call to Mat::test( < unresolved overloaded function type>, int)'

template <typename F>
int Mat::test(F f, int v){
    return f(v);
}

int Mat::f2(int x){
    return x*x;
}

int f(int x){
    return x*x;
}

void Mat::print(){
    printf("%d\n",test(f ,5));    // works
    printf("%d\n",test(f2 ,5));    // does not work
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

c++ templates function

29
推荐指数
2
解决办法
5万
查看次数

标签 统计

c++ ×4

initialization ×2

templates ×2

findbugs ×1

function ×1

variables ×1