以下示例(ideone)在Windows 7上使用Visual Studio 2013時編譯和工作,但在Ubuntu 13.10上不支持g ++ 4.8.1。爲什麼使用Visual Studio 2013編譯而不是g ++ - 4.8.1?
#include <cassert>
#include <cstdlib>
#include <array>
#include <iostream>
#include <numeric>
#include <utility>
// Wraps a std::array of TKey/TValue pairs and provides a method
// to randomly select a TKey with TValue bias.
template< typename TKey, typename TValue, std::size_t TSize >
class weights final
{
public:
using pair = const std::pair< const TKey, const TValue >;
using array = const std::array< pair, TSize >;
weights(array values)
: values_{ values }
, sum_{ std::accumulate(values_.begin(), values_.end(), 0, [](TValue total, const pair& p){ return total + p.second; }) }
{}
// Implements this algorithm
// http://stackoverflow.com/a/1761646/331024
const TKey get() const
{
// The real code uses c++11 <random> features,
// which I've removed for brevity.
auto weight_rand = static_cast<TValue>(std::rand() % sum_);
for (std::size_t i = 0; i < TSize; ++i)
{
if (weight_rand < values_[i].second)
{
return values_[i].first;
}
weight_rand -= values_[i].second;
}
assert(false);
}
private:
array values_;
const TValue sum_;
};
enum class direction
{
NORTH,
SOUTH,
EAST,
WEST
};
// For convenience create a type to map the above
// four-value enumeration to integer weights.
using w4i = weights< direction, int, 4 >;
// Map the directions with a weight.
static const w4i direction_weights = w4i::array{
{
w4i::pair{ direction::NORTH, 2 },
w4i::pair{ direction::EAST, 1 },
w4i::pair{ direction::SOUTH, 3 },
w4i::pair{ direction::WEST, 1 }
}
};
int main()
{
std::cout << (int)direction_weights.get() << std::endl;
return 0;
}
Visual Studio 2013可以編譯和運行代碼。 g ++ - 4.8.1編譯失敗,輸出如下錯誤:
$ g++ -std=c++11 -Wall -Wextra -pedantic weights.cpp -o weights
weights.cpp: In instantiation of ‘weights<TKey, TValue, TSize>::weights(array) [with TKey = direction; TValue = int; long unsigned int TSize = 4ul; weights<TKey, TValue, TSize>::array = const std::array<const std::pair<const direction, const int>, 4ul>]’:
weights.cpp:67:5: required from here
weights.cpp:20:131: error: could not convert ‘values’ from ‘weights<direction, int, 4ul>::array {aka const std::array<const std::pair<const direction, const int>, 4ul>}’ to ‘const std::pair<const direction, const int>’, sum_{ std::accumulate(values_.begin(), values_.end(), 0, [](TValue total, const pair& p){ return total + p.second; }) }
如何修改/修改它以使用兩個編譯器?
FWIW後,也將其打開砰砰聲3.4(相同/類似的錯誤)。將'values_'成員類型更改爲'const array',或者在'using array' decl中丟失'const'。 – WhozCraig
@WhozCraig感謝您的叮噹反饋。我現在擁有的和你所建議的變化之間的功能區別是什麼? –
這是一些花哨的const正確性在行動中...和一些額外的'const'以防萬一......以下情況下爲 –