一个模板链接问题,搞不定,求助
写了个简单的模板类 Urand<std::size_t N>,但链接通不过,把实现代码 Urand.cpp 合到头文件 Urand.h 中就可以通过链接,但分开却报错,求熟手帮忙诊断一下。
// Urand.h
#ifndef _URAND_H_
#define _URAND_H_
#include <bitset>
namespace zhcosin
{
template<std::size_t UpperBound>
class Urand
{
public:
Urand();
~Urand();
public:
std::size_t operator()();
private:
std::bitset<UpperBound>theBitSet;
};
} // namespace zhcosin
#endif //_URAND_H_
// Urand.cpp
#include "Urand.h"
#include <cstdlib>
#include <ctime>
namespace zhcosin
{
template<std::size_t UpperBound>
Urand<UpperBound>::Urand()
{
srand(time(0));
}
template<std::size_t UpperBound>
Urand<UpperBound>::~Urand()
{
}
template<std::size_t UpperBound>
std::size_t Urand<UpperBound>::operator ()()
{
if (theBitSet.count() == UpperBound)
theBitSet.reset();
std::size_t newVal;
while (theBitSet[newVal = rand() % UpperBound]);
theBitSet[newVal] = true;
return newVal;
}
} // namespace zhcosin
// main.cpp
#include <iostream>
#include "Urand.h"
int main(int argc, char *argv[])
{
zhcosin::Urand<10> a;
for (int i = 0; i < 10; i++)
{
std::cout << a() << ",";
}
std::cout << std::endl;
return 0;
}