模板<class T>:错误:'T'不是类型名称

3
我正在尝试编译一些在Arduino IDE中可以正常编译的代码,但使用支持Arduino的Visual Studio(Visual Micro)时出现了问题。以下是存在问题的代码:

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

我遇到的错误是:

app.ino:43:40: error: 'T' does not name a type
:int EEPROM_writeAnything(int ee, const T& value)
app.ino:43:43: error: ISO C++ forbids declaration of 'value' with no type [-fpermissive]

有人能指导我吗?

谢谢。


1
可能是ISO C++ forbids declaration of "something" with no type的重复问题。只需添加前向声明:template <class T> class value; - paulsm4
1
你使用的Arduino IDE版本是什么?当从Arduino和Visual Studio编译时,能否粘贴编译命令行?我猜它们是不同的。Visual Micro只是包装了Arduino中使用的底层gcc编译器。因此,如果在Arduino IDE中可以工作,那么在Visual Studio中也应该可以工作。 - Soundararajan
@Niall,即使我将模板函数移动到使用模板的函数之前,仍然会出现相同的错误。 - ioan ghip
1
可能是工具链中的某个问题... https://dev59.com/u3XYa4cB1Zd3GeqP4koy - Niall
1
@Niall,是的。我按照那篇帖子中的建议创建了一个头文件...看起来它有效了。谢谢! - ioan ghip
显示剩余7条评论
2个回答

6
我想我已经找到了答案。您需要在Visual Studio中手动添加函数声明。
template <class T> int EEPROM_writeAnything(int ee, const T& value);
template <class T> int EEPROM_readAnything(int ee, T& value);

但是Arduino IDE会预处理您的源代码,并在幕后为您自动添加这些内容。所以它在Arduino IDE中可以工作。

提示:当您在arduino IDE中启用详细输出时,请参考编译期间生成的中间文件保存的临时路径。它应该类似于%temp%\build0094e6ca87558f1142f08e49b0685193.tmp\sketch。它应该包含以下语句。

#line 2 "C:\\Users\\Sound\\Documents\\Arduino\\sketch_mar10d\\sketch_mar10d.ino"
template <class T> int EEPROM_writeAnything(int ee, const T& value);
#line 11 "C:\\Users\\Sound\\Documents\\Arduino\\sketch_mar10d\\sketch_mar10d.ino"
template <class T> int EEPROM_readAnything(int ee, T& value);
#line 21 "C:\\Users\\Sound\\Documents\\Arduino\\sketch_mar10d\\sketch_mar10d.ino"

想了解更多信息,请阅读此处


1
这段代码在GCC/Linux和MSVS 2015/Windows下编译都很顺利。
问题:它在Arduino IDE中能正常工作吗?
问题:使用Arduino(Visual Micro)时,是否出现“error: 'T' does not name a type”的错误?是否已联系Visual Micro?
#include <stdio.h>

typedef unsigned char byte;

class A {
public:
  void write(int & ee, const byte &p) { }
};

A EEPROM;

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

int main (int argc, char *argv[]) {
  printf ("Hello world\n");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接