由于一些奇怪的原因,我在C ++中抛出异常时遇到了困难。我没有从stdexcept头文件中捕获std::invalid_argument
而抛出。我没有真正意图捕获,因为我希望应用程序失败,如果错误发生。
在我将#include函数定义类包含到头声明的命名空间之前,似乎工作正常。它之前是在命名空间之外添加的,因为它们是模板定义,我想将标题与其定义分开;然而,我意识到这引起了一个微妙的问题,直到最近才实现。
他们缺少什么?我正在使用clang btw
Project Compilation
.
.
.
.
.
Compiling CPP file TrieTest.cpp ...
In file included from TrieTest.cpp:4:
In file included from ./Trie.hpp:62:
In file included from ./Trie.cpp:2:
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/stdexcept:55:30: error: unknown class name 'exception'; did you mean
'::std::exception'?
class logic_error : public exception
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/exception:60:9: note: '::std::exception' declared here
class exception
^
In file included from TrieTest.cpp:4:
In file included from ./Trie.hpp:62:
In file included from ./Trie.cpp:2:
/usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/stdexcept:112:32: error: expected class name
class runtime_error : public exception
^
2 errors generated.
编辑:一点src 我也编译 clang ++ -Wall -Wextra -g -std = c ++ 11 TrieTest.cpp -o TrieTest;
“Trie.h”
#ifndef COM_WORDGAME_UTILITY_TRIE_HPP
#define COM_WORDGAME_UTILITY_TRIE_HPP
#include <string>
using std::string;
namespace wordgame_utility{
template<typename value>
class Trie{
...Trie Function Declarations
};
//The compiler may not complain initialliy however
//Templates cause visibility issues with user code and is normally defined in the header
//this is a work around
#include "Trie.cpp"
}
#endif
“Trie.cpp”头-n 8
#include "Trie.hpp"
#include <stdexcept>
using namespace wordgame_utility;
template<typename value>
using TrieNode = typename Trie<value>::TrieNode;
...Trie Function Definitions
答案 0 :(得分:4)
您的代码中包含循环包含。
Trie.hpp
包括Trie.cpp
,其中包含Trie.hpp
。这并不适用于C ++,其中include
是文字包含(在#include
指令点处思考,复制/粘贴包含的文件)。
您需要在标题或第三个文件中定义模板方法,这就是全部。
这个循环有什么影响?一般来说,糟糕的错误信息,你可以自己看到。
在你的情况下......让我们自己玩预处理器:
// begin #include "Trie.hpp"
#define COM_WORDGAME_UTILITY_TRIE_HPP
// begin #include <string>
namespace std {
...
}
// end #include <string>
using std::string;
namespace wordgame_utility{
template<typename value>
class Trie{
...Trie Function Declarations
};
//The compiler may not complain initialliy however
//Templates cause visibility issues with user code
// and is normally defined in the header
//this is a work around
// begin #include "Trie.cpp"
// begin #include "Trie.hpp"
// -- empty because of the include guards --
// end #include "Trie.hpp"
// begin #include <stdexcept>
namespace std {
class logic_exception: public exception { };
}
// end #include <stdexcept>
using namespace wordgame_utility;
template<typename value>
using TrieNode = typename Trie<value>::TrieNode;
...Trie Function Definitions
// end #include "Trie.cpp"
} // namespace wordgame_utility
// end #include "Trie.hpp"
正如你所看到的,这是一团糟。在开放命名空间中使用#include
并具有循环包含的组合非常难看。
幸运的是,在(接近?)未来,如果采用模块,这将会得到改善,这只是文字包含的一个更加明智的选择。